<template>
  <div>
    <qa-view-ctrl v-for="section of currPage.sections" :key="section.id" :question="section"></qa-view-ctrl>
    <!--  提交问卷或者下一页,活动的问卷 推荐逻辑：只有一页，提交第一页内容，等完成了，结束问卷  -->
    <div class="ctrl-box">
      <!-- 这里实现普通逻辑 -->
      <a href="#" class="weui-btn_cell weui-btn_cell-default" :disabled="currPage.index === 0" :style="currPage.index === 0?'color:#aaa':''" @click="btnPrev">prev</a>
      <a href="#" class="weui-btn_cell weui-btn_cell-primary" @click="btnNext" :style="currPage.isLastPage?'display:none':''">next</a>
      <a href="#" class="weui-btn_cell weui-btn_cell-primary" @click="btnSubmit" :style="currPage.isLastPage?'':'display:none'">submit</a>
    </div>
  </div>
</template>

<script>
  // import memServ from '@/serv/memberService'
  import sdk from '@/sdk/index'
  import QaViewCtrl from '@/components/qa/view/index'
  import qaServ from '@/serv/answerService'

  export default {
    name: "doQA",
    components:{QaViewCtrl},
    data(){
      return {
        answer:null,
        currPage:{
          id:null,
          index:-1,
          sections:[],
          isLastPage:false
        }
      }
    },
    created() {
      // 因为 app里做了登录，因此这里不需要登录了
      this.doAnswer()
    },
    methods:{
      doAnswer(){
        let instanceId = 38 // 测试直接指定
        sdk.fetch({
          api:'/publics/answer/begin',
          data:{instanceId},
          success:res=>{
            console.log('answer:',res)
            this.answer = res
            this.loadCurrPage()
          },
          fail:err=>{
            console.log(err)
          }
        })
      },
      btnPrev(e){
        this.saveCurrPage(res=>{
          if(this.currPage.index>0)
            this.currPage.index --
          this.loadCurrPage()
        })
      },
      btnNext(e){
        // if(!this.currPage.isLastPage)
        //   this.currPage.index ++
        // this.loadCurrPage()
        this.saveCurrPage()
      },
      btnSubmit(e){
        this.saveCurrPage()
      },
      // 保存当前页面
      saveCurrPage(cb){
        if(this.answer.finished){
          alert('答卷已完成')
          return
        }
        // 判断是否必须
        for(let i=0;i<this.currPage.sections.length;i++){
          let sec = this.currPage.sections[i]
          if(sec.conditions.required && !sec.answer){
            //有必须的题目没有完成
            alert('题目['+sec.topic+']没有完成')
            return
          }
        }
        // 制作answer,如果有策略，也得算策略分
        console.log(this.currPage.sections)
        let scores = qaServ.countPageScore(this.currPage)
        console.log('分数看看:',scores)
        // 组装数据
        let data = {
          answerPageId:this.currPage.id,
          metadata:JSON.stringify(this.currPage.sections),
        }
        if(scores)
          data.data = JSON.stringify({scores:scores})
        // 保存答卷
        sdk.fetch({
          api:'/publics/answerPage/save',
          data,
          success:res=>{
            console.log(res)
            this.answer = res

            if(cb)
              cb(res)
            else{
              // 如果是最后一页，将提交
              if(this.currPage.isLastPage){
                // 提交
                this.finishAnswer()
              }else{
                this.currPage.index ++
                this.loadCurrPage()
              }
            }
          },
          fail:err=>{
            console.log(err)
          }
        })
      },
      finishAnswer(){
        if(this.answer.finished){
          alert('答卷已完成')
          return
        }
        // 需要客户端计算分数，有点麻烦！不安全，以后改进
        let scores = []
        this.answer.answerPages.forEach(ap => {
          if(ap.data){
            qaServ.mergeScore(scores,ap.data.scores)
          }
        })
        let data = {
          answerId:this.answer.id
        }
        if(scores.length>0)
          data.data=JSON.stringify({scores:scores})
        // 提交
        sdk.fetch({
          api:'/publics/answer/finish',
          data,
          success:res=>{
            // 寻找报告的ID号
            console.log('----finished:',res)
            if(res.data.reportDataId){
              setTimeout(this.loadReportData,1000,res.data.reportDataId)
            }
          },
          fail:err=>{
            console.log(err)
          }
        })
      },
      loadReportData(id){
        sdk.fetch({
          api:'/publics/reportData/get',
          data:{id},
          success: res=>{
            console.log(res)
          }
        })
      },
      loadCurrPage(){
        if(this.answer.finished){
          alert('答卷已完成')
          return
        }
        // 加载当前页面   <0 表示未初始化,如果已经初始化 不会加载服务器端当前页面
        if(this.currPage.index<0 && this.answer.currentPage){
          // 找到当前页索引,服务器数据里用已经完成的当前页面
          let tIdx = this.answer.answerPages.findIndex(ap => ap.id === this.answer.currentPage)
          if(tIdx >= 0 && tIdx < this.answer.answerPages.length -1)
            this.currPage.index = tIdx+1
          else
            this.currPage.index = tIdx
        }else {// 否者就是 索引 0
          //
          if(this.currPage.index<0)
            this.currPage.index = 0
        }
        // 判断是否最后一夜
        if(this.currPage.index === this.answer.answerPages.length - 1)
          this.currPage.isLastPage=true
        else
          this.currPage.isLastPage=false
        console.log('curr page:',this.currPage)
        // console.log(this.answer.answerPages[this.currPage.index].metadata)
        this.currPage.id = this.answer.answerPages[this.currPage.index].id
        this.currPage.sections = JSON.parse(this.answer.answerPages[this.currPage.index].metadata)
        // console.log(this.currPage.sections)
        // 其他再说
      }
    }
  }
</script>

<style scoped>
  .ctrl-box{
    display: flex;
    flex-direction: row;

  }
</style>
